package com.zbcz.erp.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zbcz.erp.ErpApplication
import com.zbcz.erp.bean.LoginRequestBean
import com.zbcz.erp.bean.LoginResult
import com.zbcz.erp.bean.UserInfo
import com.zbcz.erp.network.ErpApi
import com.zbcz.erp.network.RetrofitManager
import com.zbcz.erp.sp.SharedPreferencesManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random


class LoginViewModel : ViewModel() {

    private val mApi = RetrofitManager.getRetrofit()?.create(ErpApi::class.java)

    var mLoginResponse: MutableLiveData<UserInfo?> = MutableLiveData()


    companion object {
        fun generateRandomFiveDigitNumber(): String {
            val random = Random(System.currentTimeMillis())
            return random.nextInt(10000, 99999).toString() // 生成一个范围在10000到99999之间的随机数
        }

        fun extractBase64ImageData(base64String: String): String? {
            val prefix = "base64," // 前缀
            val startIndex = base64String.indexOf(prefix) // 寻找前缀的位置
            return if (startIndex != -1) {
                base64String.substring(startIndex + prefix.length) // 提取实际图像数据部分
            } else {
                null // 如果没有找到前缀，则返回空
            }
        }
    }

    fun login(userName: String, password: String?) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val loginResult = loginRequest(LoginRequestBean(userName, password))
                mLoginResponse.postValue(loginResult?.userInfo)
                SharedPreferencesManager.putToken(loginResult?.token ?: "", ErpApplication.mApplication)
            }
        }
    }


    private suspend fun loginRequest(loginRequestBean: LoginRequestBean): LoginResult? {
        try {
            val result = mApi?.login(loginRequestBean)
            if (result?.code == 200) {
                return result.result
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}